# -*- coding: utf-8 -*-
'''
@文件    :requestFunc.py
@说明    :
@时间    :2023/12/04 21:57:27
@作者    :浪晋
@版本    :1.0
'''


import re

def pageConvert(pageNum,pageSize):
    """
    @功能    :处理sql中limit的起始数
    @参数    :
    @返回值  :
    @时间    :2022/11/14 23:45:47
    @作者    :浪晋
    @版本    :1.0
    """
    if pageNum == 1:
            pageNum = 0
    else:
        pageNum = (pageNum - 1) * pageSize
    return pageNum,pageSize


class RequestParser:
    """
    这是一个通用的对接口的参数进行校验的类
    """
    def __init__(self):
       self.args = []

    def add_argument(self,value,name:str,remark:str,**kwargs):
        """
        接收需要校验的参数\n
        name,参数的中文名\n
        value,参数的值\n
        required,是否必填,True/False\n
        lenght,字符串的长度范围或者数字的范围,()\n
        type,参数允许的类型，()\n
        remark,参数的规则说明\n
        regex,正则表达式
        """
        data = {
            "name":name,
            "value":value,
            "remark":remark,
            "required":kwargs.get("required"),
            "types":kwargs.get("type"),
            "lenght":kwargs.get("lenght"),
            "regex":kwargs.get("regex")
        }
        self.args.append(data)


    def parse_args(self):
        args = self.args
        for data in args:
            value = data.get("value")
            name = data.get("name")
            remark = data.get("remark")
            required = data.get("required")
            types = data.get("types")
            lenght = data.get("lenght")
            regex = data.get("regex")
            
            if required:
                if value == None:
                    return f"{name}要求{remark}"
            if types and value is not None:
                try:
                    if not isinstance(value,types):
                        return f"{name}要求{remark}"
                except:
                    raise Exception("types必须是数组或者元组类型")
            if lenght and value is not None:
                try:
                    if isinstance(value,(int,float)):
                        if value < lenght[0] or  value > lenght[1]:
                            return f"{name}要求{remark}"
                    else:
                        if len(value) < lenght[0] or  len(value) > lenght[1]:
                            return f"{name}要求{remark}"
                except:
                    raise Exception("lenght必须是数组或者元组类型,并且长度为2")
            if regex and value not in (None,""):
                try:
                    result =  re.fullmatch(regex,str(value))
                    if not result:
                        return f"{name}要求{remark}"
                except:
                    raise Exception(f"正则表达式{regex}不正确")


        return False
                


if __name__ == "__main__":
    parser = RequestParser()
    parser.add_argument("username","账号","不能为空",required=True,lenght=(5,12),type=(str))
    parser.add_argument("fenhuyd@163.com","邮箱","必填邮箱",regex=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    result = parser.parse_args()
    print(result)
            



